<template>
  <el-col :sm="12" :lg="6" v-if="this.isSucess == true" class="error">
    <el-result icon="success" title="成功提示" subTitle="提交成功">
    </el-result>
  </el-col>
  <el-col :sm="12" :lg="6" v-else-if="this.isExist == false" class="error"> 
    <el-result icon="error" title="错误提示" subTitle="问卷不存在">
    </el-result>
  </el-col>
  <el-col :sm="12" :lg="6" v-else-if="this.isPosted == false" class="error"> 
    <el-result icon="error" title="错误提示" subTitle="问卷未发布">
    </el-result>
  </el-col>
  <el-col :sm="12" :lg="6" v-else-if=" this.isFitTime() " class="error"> 
    <el-result icon="error" title="错误提示" subTitle="不在问卷填写时间内">
    </el-result>
  </el-col>
  <el-col :sm="12" :lg="6" v-else-if="this.isSubmitted == true" class="error"> 
    <el-result icon="error" title="错误提示" subTitle="问卷已提交过">
    </el-result>
  </el-col>
  <div class="all" v-else>
    <div class="date" v-if="this.isDate && !this.isFitTime()" style="max-width:25%; position: absolute;top:3rem; right:3rem;">
      <div>距离问卷截止时间</div>
      <div>{{getTime()}}</div>
    </div> 
  <div id="fill">
    
    <div>

      <div class="title">{{title}}</div>
      <div class="description">{{description}}</div>
      <div v-for="(question, index) in questions">
        <div v-if="question.isShow&&question.type == 'radio'">
          <radio  
          :no="getno(index)"
          :question="question"
          :radio="getRadio(question)"
          @changeRadio="changeRadio"
          >
          </radio>
        </div>
        

        <check-box 
        v-if="question.isShow&&question.type == 'checkbox'"
        :no="getno(index)"
        :question="question"
        :checkList="getCheckBox(question)"
        @changeCheckBox="changeCheckBox"
        >
        </check-box>

        <completion
        v-if="question.isShow&&question.type == 'completion'"
        :no="getno(index)"
        :question="question"
        :input="getInput(question)"
        @changeCompletion="changeCompletion"
        >
        </completion>

        <star
        v-if="question.isShow&&question.type == 'score'"
        :no="getno(index)"
        :question="question"
        :max="question.options.length-1"
        :score="getScore(question)"
        @changeRadio="changeRadio"
        >
        </star>
      </div>
      <div class="button"><el-button type="primary" plain @click="submit">提交</el-button></div>
    </div>
    
  </div>
  </div>
</template>

<script>
import Radio from '../question/Radio.vue'
import CheckBox from '../question/CheckBox.vue'
import Completion from '../question/Completion.vue'
import Star from '../question/Star.vue'
import axios from "axios"
import qs from "qs"
import { h } from 'vue';
import {jsonp} from 'vue-jsonp'
import {initQRelation} from "../relation";

export default {
  name:'Fill',
  components: {
    Radio,
    CheckBox,
    Completion,
    Star,
  },
  data(){
   return {
     id: 0,
     title: '题目',
     isPosted: false,
     description: '123456665',
     isAutoLabel: true,
     isSubmitted: false,
     questions: [],
     isSucess: false,
     isExist: true,
     type: 'base',
     randomType: '',
     result: null,
     isAutoSubmit: false,
     begin: null,
     end: null,
     date: new Date(),
     isDate: false,
     autoSubmit: false,
     beforefit: false,
   }
  },
  mounted() {
    
  },
  destroyed() {
	  if (this.timer) {
    	clearInterval(this.timer); // 在Vue实例销毁前，清除当前日期定时器
    };
  },
  created: function (){
    this.getAddress()
    this.getQAbaseData()
  },
  methods: {
    isFitTime() {
      if(this.isDate == false) {
        return false
      }
      if(Date.parse(this.begin) < this.date && Date.parse(this.end) > this.date) {
        this.beforefit = true
        return false
      }else{
        console.log(this.beforefit);
        if(this.beforefit == true && this.autoSubmit == false) {
          if(this.isAutoSubmit) {
            this.submit()
          }
          this.autoSubmit = true
          this.beforefit = false
        }
        if (this.timer) {
          clearInterval(this.timer); // 在Vue实例销毁前，清除当前日期定时器
        };
        return true
      }
    },

    getTime() {
      let diff = (Date.parse(this.end) - this.date)
      diff = Math.floor(diff / 1000)
      const s = diff % 60
      diff = Math.floor(diff / 60)
      const m = diff % 60
      diff = Math.floor(diff / 60)
      const h = diff % 60
      diff = Math.floor(diff / 60)
      const d = diff % 24
      diff = Math.floor(diff / 60)
      return d+'天'+h+'时'+m+'分'+s+'秒'
    },

    getno(index) {
      if(!this.isAutoLabel) {
        return 0
      }else{  
        return index+1
      }
    },

    getdata(res) {
      return res.data.data
    },

    getRadio(question) {
      if(question.answer == null) {
        return null
      }else {
        return question.answer[0]
      }    
    },

    getScore(question) {
      if(question.answer == null) {
        return 0
      }else {
        for(let option of question.options) {
          if(option.id == question.answer[0]) {
            return option.score
          }
        }
      }
    },

    getCheckBox(question) {
      return question.answer
      // if(question.optionIds != null) {
        
      //   return question.optionIds
      // }
      // question.optionIds = []
      // question.options.forEach(option => {
      //   if(option.isDefault) {
      //     question.optionIds.push(option.id)
      //   }
      // });   
      // this.changeCheckBox(question)
      // return question.optionIds
    },

    getInput(question) {
      if(question.content != null) {
        return question.content
      }else{
        return ''
      }
    },

    getQuestionnaireData() {
      let data = {
        id: this.userId,
        questionnaireId: this.id,
        uuid: this.uuid,
      }
      console.log(data);
      axios.post('/api/fill/getq',qs.stringify(data)).then(res => {
        console.log(res);
        if(res.data.code == 0) {

          //TODO  初始化关联关系
            if(res.data.data.relations!=null){
                let caller = res.data.data.relations.caller;
                let relationMap = res.data.data.relations.relationMap;
                let questions = res.data.data.questions;
                if(Object.keys(caller).length>0){
                    initQRelation(res.data.data.questions,relationMap);
                    //计算关联
                    if(questions.length!==0){
                        let question = questions[0];
                        question.isShow=true;
                        questions.forEach(each=>{
                            if(each.isShow){
                                each.call();
                            }
                        })
                    }
                }
            }

          this.questions = this.getdata(res)['questions']
        }else {
          console.log(res)
        }
      })
    },

    getQAbaseData() {
      let data = {
        uuid: this.questionnaireId
      }
      console.log(data);
      axios.post('/api/fill/getqaInfo',qs.stringify(data)).then(res => {
        console.log(res.data);
        if(res.data.code == 0) {
          this.id = this.getdata(res)['id']
          this.title = this.getdata(res)['title']
          this.description = this.getdata(res)['description']
          this.type = this.getdata(res)['type']
          this.isAutoLabel = this.getdata(res)['isAutoLabel']
          this.isPosted = this.getdata(res)['isPosted']
          this.isNeedLogin = this.getdata(res)['isNeedLogin']
          this.randomType = this.getdata(res)['randomType']
          this.isAutoSubmit = this.getdata(res)['isAutoSubmit']
          this.begin = this.getdata(res)['beginDate']
          this.end = this.getdata(res)['endDate']
          this.isDate = this.getdata(res)['isDate']
          if(this.isDate) {
            var _this = this;
            this.timer = setInterval(() => {
              _this.date = new Date(); // 修改日期数据
            }, 1000);
          }
          this.isLogin()  
          this.getIsSubmitted()
        }else if(res.data.code == -1){
          this.isExist = false
        }else {
          console.log(res)
        }
      })
    },

    getAddress() {
      let data = {
        key: 'CCYBZ-257K4-UL7UB-X4FDY-I5LNS-JMF6J',
        output: 'jsonp'
      }
      let url = "https://apis.map.qq.com/ws/location/v1/ip"
      jsonp(url, data).then(res => {
        console.log(res);
        if(res.status == 0){
          this.result = res
        }
      })
    },

    isLogin() {
      if(this.isExist && this.isPosted && this.isNeedLogin) {
        if(this.userId == null) {
          const { href } = this.$router.resolve({
            path: '/login',
          });
          window.open(href,'_blank')
          return
        }
      }
    },

    getIsSubmitted() {
      let data = {
        id: this.userId,
        questionnaireId: this.id,
        uuid: this.uuid,
      }
      console.log(data);
      axios.post('/api/fill/isSubmitted',qs.stringify(data)).then(res => {
        console.log(res);
        if(res.data.code == 0)  {
          this.isSubmitted = this.getdata(res).isSubmitted
          window.localStorage.setItem('uuid', this.getdata(res).uuid)
          
          this.getQuestionnaireData()
        } else 
          console.log(res);
      })
    },

    changeRadio(question) {
      console.log(question);
      console.log(this.questions);
      for(let item of this.questions) {
        if(item.id == question.id && item.type == question.type) {
          item = question
          let data = {
            id: this.userId,
            questionId: question.id,
            optionId: question.answer[0],
            questionnaireId: this.id,
            uuid: this.uuid
          }
          console.log(data);
          if(question.type == 'radio')
            axios.post('/api/fill/submitRadio',qs.stringify(data)).then(res => {
              if(res.data.code == 0) {
                
              }else {
                console.log(res)
              }
            })
          else
            axios.post('/api/fill/submitScore',qs.stringify(data)).then(res => {
              if(res.data.code == 0) {
                
              }else {
                console.log(res)
              }
            })
        }
      }
    },

    changeCheckBox(question) {
      if( this.isSubmitted == false) {
      for(let item of this.questions) {
        if(item.id == question.id && item.type == question.type) {
          item = question
          let data = {
            id: this.userId,
            questionId: question.id,
            questionnaireId: this.id,
            uuid: this.uuid,
            options: question.answer,
          }
          axios.post('/api/fill/submitCheckBox',data).then(res => {
            if(res.data.code == 0) {
              
            }else {
              console.log(res)
            }
          })
        }
      }
      }
    },

    changeCompletion(question) {
      if( this.isSubmitted == false) {
      for(let item of this.questions) {
        if(item.id == question.id && item.type == question.type) {
          item = question
          let data = {
            id: this.userId,
            questionId: question.id,
            questionnaireId: this.id,
            uuid: this.uuid,
            content: question.content,
          }
          
          axios.post('/api/fill/submitCompletion', qs.stringify(data)).then(res => {
            if(res.data.code == 0) {
            }else {
              console.log(res)
            }
          })
        }
      }
      }
    },
    
    notSubmit(question) {
      switch(question.type) {
        case "radio": 
        case 'score':
        case 'checkbox':
          if(question.answer == null){
            return false
          }else {
            return true
          }
          break
        case 'completion':
          if(question.content === null||question.content===""){
            return false
          }else {
            return true
          }
          break
      }
    },

    notAll() {
      this.$notify({
        title: '错误',
        message: h('i', { style: 'color: teal'}, '还有必填问题未填写')
      });
    },

    success() {
      this.isSucess = true
    },

    submit() {
        for(let question of this.questions) {
          if(question.isShow && question.isNecessary && !this.notSubmit(question)){
            this.notAll()
            return
          }
        }
        let data = {
          id: this.userId,
          questionnaireId: this.id,
          uuid: this.uuid,
          ipBody: this.result,
          type: 'exam',
        }
        axios.post('/api/fill/userSubmit',data).then(res => {
          if(res.data.code == 0) {
            this.isSucess = true
            const { href } = this.$router.resolve({
              path: '/fill/exam/grade',
              query: {
                recordId: res.data.data
              }
            });
            window.open(href,'_self')
          }else if(res.data.code == -1){
            this.isSubmitted = true
          }
          else {
            console.log(res)
          }
        }) 
    },

    getPosition() {
        this.$confirm('请求获取您的位置信息', '提示', {
          confirmButtonText: '允许',
          cancelButtonText: '拒绝',
          type: 'warning'
        }).then(() => {
          this.$message({
            type: 'success',
            message: '获取位置成功!'
          });
        }).catch(() => {
          // this.$message({
          //   type: 'info',
          //   message: '已取消删除'
          // });
        });
      }
  },
  computed:{
    questionnaireId(){
      return this.$route.query.questionnaireId
    },
    userId() {
      // if(localStorage.getItem('id') == null || localStorage.getItem('id') == '')
      //   return null
      // else
      //   return parseInt(localStorage.getItem('id'))
      return localStorage.getItem("id");
    },
    uuid() {
      if(localStorage.getItem('uuid') == 'NaN' || localStorage.getItem('uuid') == null || localStorage.getItem('uuid') == '') {
        return null
      }
      return localStorage.getItem('uuid') 
    }
  }
}
</script>

<style scoped src='assets/css/fillcss/fill.css'>
</style>
